<template>
	<section v-loading="listLoading">
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item class="fr">
				    <el-button type="primary" size="medium" plain @click="handleAdd">新增</el-button>
			   </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="list" stripe highlight-current-row border @selection-change="selsChange" style="width: 100%;">
			<!--<el-table-column type="selection" min-width="40" align="center">
			</el-table-column>-->
            <el-table-column prop="categoryId" label="ID" min-width="60" align="center">
			</el-table-column>
			<el-table-column prop="categorynNme" label="名称" min-width="60" align="center">
			</el-table-column>
			<el-table-column prop="picUrl" label="图片" align="center" min-width="100">
				<template slot-scope="scope">
                    <el-popover placement="top-start" title="" trigger="click">
                        <img :src="scope.row.picUrl" alt="" style="width: 500px">
                        <img slot="reference" :src="scope.row.picUrl" style="width: 50px;height: 50px;border-radius: 5px;object-fit: cover;">
                    </el-popover>
                </template>
            </el-table-column>
			
			<el-table-column label="操作" width="200" align="center">
				<template slot-scope="scope">
					<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="mini" plain @click="handleDel(scope.row.categoryId)">删除</el-button>
					<el-button size="mini" type="success" plain @click="xinleimuChild(scope.$index, scope.row, 'xinleimuChild')">二级</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<!--<el-col :span="24" class="toolbar">
			
			<el-pagination layout="prev, pager, next, jumper" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>-->
		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false" width="500px">
			<el-form :model="addForm" label-width="80px" ref="addForm">
				<el-form-item label="名称" prop="categorynNme">
                    <el-input v-model="addForm.categorynNme"/>
                </el-form-item>
				<el-form-item label="图片:" prop="picUrl">
					<el-upload class="avatar-uploader photo" list-type="picture-card" :http-request="(res)=>{return Upload1(res, 'picUrl')}" :multiple="false" :show-file-list="false" action="" :before-upload="beforeAvatarUpload" accept="image/jpeg,image/png">
						<img v-if="addForm.picUrl" :src="addForm.picUrl" class="avatar" width="145" height="145">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
				
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click.native="addFormVisible = false">取消</el-button>
				<el-button size="mini" type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
		<!--编辑界面-->
		<el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false" width="500px">
			<el-form :model="editForm" label-width="80px" ref="editForm">
				<el-form-item label="名称" prop="categorynNme">
                    <el-input v-model="editForm.categorynNme"/>
                </el-form-item>
				<el-form-item label="图片:" prop="picUrl">
					<el-upload class="avatar-uploader photo" list-type="picture-card" :http-request="(res)=>{return Upload2(res, 'picUrl')}" :multiple="false" :show-file-list="false" action="" :before-upload="beforeAvatarUpload" accept="image/jpeg,image/png">
						<img v-if="editForm.picUrl" :src="editForm.picUrl" class="avatar" width="145" height="145">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click.native="editFormVisible = false">取消</el-button>
				<el-button size="mini" type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import { client } from '../../common/js/alioss'
	import util from '../../common/js/util'

	export default {
		data() {
			return {
				
				filters: {
					content: '',
				},
                data:{},
				list: [],
				data:[],
				sels: [],
				total: 0,
				page: 1,
				pageSize: 10,
				listLoading: false,
				
				addFormVisible: false,
				addLoading: false,
				addForm: {
					picUrl: '',
					categorynNme:''
				},
				editFormVisible: false,
				editLoading: false,
				editForm: {
					categoryId: '',
					picUrl: '',
					categorynNme:''
				}
				
			}
		},
		
		methods: {
			//评论
			xinleimuChild(index, row, href) {
				console.log(href, '1')
				this.$router.push({
					path: '/' + href,
					query: {
						id: row.categoryId
					}
				})
			},
			//时间转换开始时间 
			formatDate(row, column) {
                let date = new Date(parseInt(row.createTime));
                let Y = date.getFullYear() + '-';
                let M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) + '-' : date.getMonth() + 1 + '-';
                let D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' ';
                let h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':';
                let m = date.getMinutes()  < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':';
                let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
                return Y + M + D + h + m + s;
            },
			//添加图片
			dialogClose(){
                this.fileList = [];
            },
			
			beforeAvatarUpload(file) {
//              this.listLoading = true;
			},//图片上传到阿里云
            Upload1(file, index) {
				var fileName = 'webStorage/web_' + file.file.uid+Math.floor(Math.random()*10000) + file.file.name.substr(file.file.name.indexOf("."));
				client().put(fileName, file.file).then(result => {
					this.addForm[index] = result.url;
					console.log(this.addForm[index]);
				}).catch(function (err) {
                    console.log(err);
	 			});
            },
            Upload2(file, index) {
				var fileName = 'webStorage/web_' + file.file.uid+Math.floor(Math.random()*10000) + file.file.name.substr(file.file.name.indexOf("."));
				client().put(fileName, file.file).then(result => {
					this.editForm[index] = result.url;
				}).catch(function (err) {
                    console.log(err);
	 			});
           },
			handleCurrentChange(val) {
				this.page = val;
				this.getUsers();
			},
			//获取用户列表
			getUsers:function (){
				this.listLoading = true;
				let para = {
					page: this.page,
					size: this.pageSize,
				};
				var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
			    });  
			    instance.post('admin/newCategory/getFatherCategoryList', this.qs.stringify(para)).then(data => {
					let  res = data.data;
					console.log(data);
					if (res.code !== 0) {
						this.$message({
							message: res.msg,
							type: 'error'
						});
					} else {
						console.log(res)
						this.total = res.total;
						this.list = res.rows;
						this.listLoading = false;
					}
				});
			},
			
			selsChange: function (sels) {
				this.sels = sels;
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
					picUrl: '',
					categorynNme:''
				};
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
                            let para = Object.assign({}, this.addForm);
                            var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
						    });  
						    instance.post('admin/newCategory/addCategoryOrUpd', this.qs.stringify(para)).then(data => {
											let  res = data.data;
								if (res.code !== 0) {
									this.$message({
										message: res.msg,
										type: 'error'
									});
								} else {
									this.addLoading = false;
									this.$message({
										message: '成功',
										type: 'success'
									});
									this.$refs['addForm'].resetFields();
									this.addFormVisible = false;
									this.getUsers();
								}
							});
						});
					}
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				
				this.editFormVisible = true;
				this.editForm.categoryId = row.categoryId;
				this.editForm.categorynNme = row.categorynNme;
				this.editForm.picUrl = row.picUrl;
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							let para = {
								categoryId:this.editForm.categoryId,
								categorynNme:this.editForm.categorynNme,
								picUrl:this.editForm.picUrl,
							}
							var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
						    });  
						    instance.post('admin/newCategory/addCategoryOrUpd', this.qs.stringify(para)).then(data => {
								
								let  res = data.data;
								if (res.code !== 0) {
									this.$message({
										message: res.msg,
										type: 'error'
									});
								} else {
									this.editLoading = false;
									this.$message({
										message: '提交成功',
										type: 'success'
									});
									this.$refs['editForm'].resetFields();
									this.editFormVisible = false;
									this.getUsers();
								}
							});
						});
					}
				});
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.handleDel(ids);
			},
			//删除
			handleDel(id) {
				this.$confirm('确认删除吗?', '提示', {}).then(() => {
					this.listLoading = true;
					var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
				    });  
				    instance.post('admin/newCategory/delCategory', this.qs.stringify({categoryId: id})).then(data => {
						
						let  res = data.data;
						if (res.code !== 0) {
							this.$message({
								message: res.msg,
								type: 'error'
							});
						} else {
							this.$message({
								message: '成功',
								type: 'success'
							});
							this.getUsers();
						}
					})
				}).catch(() => {

				});
			},
		},
		mounted() {
			this.getUsers();
		}
	}

</script>
<style>

</style>

<style>
	.advice{
		margin-left: 80px;
		margin-bottom: 10px;
		font-size: 12px;
	}
</style>

